/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.transform.csv;

import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.support.transform.AbstractTransformer;
import cn.easyplatform.support.transform.Parameter;
import cn.easyplatform.type.FieldType;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CsvToTableTransformer extends
        AbstractTransformer<String, Map<String, List<List<FieldDo>>>> {

    @Override
    public void transform(String src, Parameter parameter) {
        String lineSep = parameter.getSheets()[0];
        char cellSep = parameter.getSheets()[1].charAt(0);
        String[] lines = StringUtils.split(src, lineSep);
        Map<String, List<List<FieldDo>>> data = new HashMap<String, List<List<FieldDo>>>();
        List<List<FieldDo>> records = new ArrayList<List<FieldDo>>();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (Strings.isBlank(line))
                continue;
            char[] values = line.toCharArray();
            boolean beginQuote = false;
            sb.setLength(0);
            int index = 1;
            List<FieldDo> record = new ArrayList<FieldDo>();
            for (int i = 0; i < values.length; i++) {
                if (values[i] == '"')
                    beginQuote = !beginQuote;
                if (!beginQuote && values[i] == cellSep) {
                    record.add(new FieldDo(String.valueOf(index++),
                            FieldType.VARCHAR, sb.toString().trim()));
                    sb.setLength(0);
                } else if (values[i] != '"')
                    sb.append(values[i]);
            }
            records.add(record);
        }
        data.put("1", records);
        handler.transform(data, parameter);
    }
}
